package com.bm.specialvehiclefordispatcher.activity.mywallet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.Tools.Tools;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.alipay.AlipayHelper;
import com.bm.specialvehiclefordispatcher.alipay.PayResult;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.constants.Urls;
import com.bm.specialvehiclefordispatcher.logics.LoginManager;
import com.bm.specialvehiclefordispatcher.logics.UnionPayManager;
import com.bm.specialvehiclefordispatcher.views.CommonNavigationBar;
import com.unionpay.UPPayAssistEx;

public class RechargeMoneyActivity extends BaseActivity implements OnClickListener {

	CommonNavigationBar bar;
	EditText rechargemoney_edit;
	LinearLayout zhifubao;
	LinearLayout yinlian;
	ImageView zhifubao_sure;
	ImageView yinlian_sure;
	Button rechargemoney_sure;
	// 0为支付宝 1为银联
	int type = -1;

	/*****************************************************************
	 * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
	 *****************************************************************/
	private final String mMode = "00";
	private static final String TN_URL_01 = Urls.ROOT + "unionPay.htm";
	/**
	 * 支付插件正常
	 */
	public static final int PLUGIN_VALID = 0;
	/**
	 * 支付插件未安装
	 */
    public static final int PLUGIN_NOT_INSTALLED = -1;
    /**
     * 支付插件需要升级
     */
    public static final int PLUGIN_NEED_UPGRADE = 2;
	private String TN;
	private UnionPayManager manager = new UnionPayManager();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rechargemoney);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		bar = (CommonNavigationBar) findViewById(R.id.navi);
		bar.setListener(null);
		bar.setTitle("选择充值方式");
		rechargemoney_edit = (EditText) findViewById(R.id.rechargemoney_edit);
		zhifubao = (LinearLayout) findViewById(R.id.zhifubao);
		yinlian = (LinearLayout) findViewById(R.id.yinlian);
		zhifubao_sure = (ImageView) findViewById(R.id.zhifubao_sure);
		yinlian_sure = (ImageView) findViewById(R.id.yinlian_sure);
		rechargemoney_sure = (Button) findViewById(R.id.rechargemoney_sure);
	}

	@Override
	public void init() {

	}

	@Override
	public void addListeners() {
		zhifubao.setOnClickListener(this);
		yinlian.setOnClickListener(this);
		rechargemoney_sure.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.zhifubao:
			type = 0;
			zhifubao_sure.setBackgroundResource(R.drawable.register_agree);
			yinlian_sure.setBackgroundResource(R.drawable.register_disagree);
			break;
		case R.id.yinlian:
			type = 1;
			zhifubao_sure.setBackgroundResource(R.drawable.register_disagree);
			yinlian_sure.setBackgroundResource(R.drawable.register_agree);
			break;
		case R.id.rechargemoney_sure:
			if (Tools.getTextViewText(rechargemoney_edit).length() > 0) {
				//if ((Double.parseDouble(Tools.getTextViewText(rechargemoney_edit))) >= 1) {
					if (type == -1) {
						showToast("请选择一种支付方式");
					} else {
						if (type == 0) {
							if (!isButtonClicked)
								payWithAilpay(Double.parseDouble(Tools.getTextViewText(rechargemoney_edit)));
							isButtonClicked = true;
						}

						if (type == 1) {
							getTn();
						}

						// startActivity(new Intent(mActivity,
						// RechargeResult.class));
						// finish();

					}

//				} else {
//					showToast("充值金额必须大于1元");
//				}
			} else {
				showToast("请输入充值金额");
			}
			break;

		default:
			break;
		}
	}

	private static final int RQF_PAY = 1;

	//private Intent intent;

	private boolean isButtonClicked = false;

	@SuppressLint("HandlerLeak")
	private Handler mPayHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			PayResult payResult = new PayResult((String) msg.obj);
			String resultStatus = payResult.getResultStatus();
			switch (msg.what) {
			case RQF_PAY:
				isButtonClicked = false;
				if (TextUtils.equals(resultStatus, "9000")) {
					// updatePayResult();
					// intent = new Intent(getApplicationContext(), PayResultActivity.class);
					// intent.putExtra("PAY_RESULT", Constant.PAY_RESULT_OK);
					// startActivity(intent);
					ToastMgr.show("充值成功, 请耐心等待支付结果");
					setResult(RESULT_OK);
					finish();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						ToastMgr.show("支付结果确认中");
					} else {
						if (TextUtils.equals(resultStatus, "6001")) {
							// 手动取消
						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						}
						ToastMgr.show("支付失败");
						// intent = new Intent(getApplicationContext(), PayResultActivity.class);
						// intent.putExtra("PAY_RESULT", Constant.PAY_RESULT_ERR);
						// startActivity(intent);
					}
				}
				break;
			}
		}
	};

	private void payWithAilpay(final double d) {
		// start the pay.
		new Thread() {
			@Override
			public void run() {
				String subject = "充值金额：" + d;
				String notify_url = AlipayHelper.getNotifyUrl();
				System.out.println(notify_url);
				String orderInfo = AlipayHelper.getOrderInfo(subject, "充值", d + "", notify_url, null);
				System.out.println(orderInfo);
				String sign = AlipayHelper.sign(orderInfo);
				System.out.println(sign);
				try {
					// 仅需对sign 做URL编码
					sign = URLEncoder.encode(sign, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				// 完整的符合支付宝参数规范的订单信息
				final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + AlipayHelper.getSignType();
				// AliPay alipay = new AliPay(MyChargeActivity.this, mPayHandler);
				System.out.println(payInfo);
				PayTask alipay = new PayTask(RechargeMoneyActivity.this);
				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);

				String result = alipay.pay(payInfo);

				System.out.println(result);

				Message msg = new Message();
				msg.what = RQF_PAY;
				msg.obj = result;
				mPayHandler.sendMessage(msg);
			}
		}.start();
	}

	private void payWithUnion() {
		int ret = UPPayAssistEx.startPay(this, null, null, TN, mMode);
        if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("完成充值需要安装银联支付控件，是否安装？");

            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UPPayAssistEx.installUPPayPlugin(RechargeMoneyActivity.this);
                            dialog.dismiss();
                        }
                    });

            builder.setPositiveButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();

        }
	}
	
	private void getTn() {
		loadingDialog.show();
		manager.getTn(TN_URL_01, LoginManager.getInstance(mActivity).getId(), Double.parseDouble(Tools.getTextViewText(rechargemoney_edit)), listener);
	}
	
	private NListener<BaseData> listener = new NListener<BaseData>() {
		@Override
		public void onResponse(BaseData data) {
			loadingDialog.dismiss();
			if(data.status == Constant.STATUS_OK) {
				TN = data.data.unionInfo.tn;
				payWithUnion();
			} else {
				ToastMgr.show(data.msg);
			}
		}
		@Override
		public void onErrResponse(VolleyError error) {
			loadingDialog.dismiss();
		}
		@Override
		public void onAllPageLoaded(int nowPage, int totalPage) {}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null) {
			return;
		}
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		if (str.equalsIgnoreCase("success")) {
			ToastMgr.show("支付成功");
			setResult(RESULT_OK);
			finish();
		} else if (str.equalsIgnoreCase("fail")) {
			ToastMgr.show("支付失败, 请稍后再试");
		} else if (str.equalsIgnoreCase("cancel")) {
			ToastMgr.show("支付已取消");
		}
	}

}
